package com.mz.ozy.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Base64;


import com.mz.ozy.WpkApp;
import com.mz.ozy.bean.LoginBean;
import com.mz.ozy.constants.Constants;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by dengzh on 2018/4/18.
 */

public class AppUtils {

    /**
     * 保存登录的静态数据
     *
     * @param loginBean
     * @param type
     */
    public static void saveLoginData(Context context, LoginBean loginBean, int type) {
        //本地保存token和用户名
        SPUtils.getInstance(context).putString(Constants.PREE.SESSION_ID, loginBean.getSessionId());
        SPUtils.getInstance(context).putString(Constants.PREE.TOKEN_ID, loginBean.getT());
        SPUtils.getInstance(context).putString(Constants.SPName.USERNAME, loginBean.getUsername());
        SPUtils.getInstance(context).putString(Constants.SPName.QINIU_TOKEN, loginBean.getUpToken());
        SPUtils.getInstance(context).putString(Constants.SPName.IS_LOGIN, "1");
        SPUtils.getInstance(context).putString(Constants.PREE.UID, loginBean.getUid());
        Constants.isLogin = true;
        Constants.tokenId = SPUtils.getInstance(context).getString(Constants.PREE.TOKEN_ID, "");
        Constants.uid = SPUtils.getInstance(context).getString(Constants.PREE.UID, "");
        if (!TextUtils.isEmpty(Constants.uid)) {
            JPushInterface.setAlias(WpkApp.ctx.getApplicationContext(), 1, Constants.uid);
        }

        //是否已设置支付密码
        if (loginBean.getPwdnum() == 1 || type == LoginBean.LOGIN_TYPE_PASS) {//已设置
            SPUtils.getInstance(context).putString(Constants.PREE.IS_PAY_PWD, "1");
            Constants.isPayPwd = true;
        } else {//未设置
            SPUtils.getInstance(context).putString(Constants.PREE.IS_PAY_PWD, "0");
            Constants.isPayPwd = false;
        }

        //是否是年卡会员
        if (loginBean.getGrade() == 0) {
            SPUtils.getInstance(context).putString(Constants.PREE.IS_VIP, "0");
            Constants.isVip = false;
        } else {
            SPUtils.getInstance(context).putString(Constants.PREE.IS_VIP, "1");
            Constants.isVip = true;
        }
    }

    /**
     * 重置静态数据
     *
     * @param context
     */
    public static void resetStaticData(Context context) {
        //注销  重置某些数据
        Constants.tokenId = "";
        Constants.isLogin = false;
        Constants.isPayPwd = false;
        Constants.isVip = false;
        Constants.uid = null;

        JPushInterface.deleteAlias(WpkApp.ctx.getApplicationContext(), 1);
        SPUtils.getInstance(context).remove(Constants.SPName.IS_LOGIN);
    }

    /**
     * 手机号号段校验，
     * 第1位：1；
     * 第2位：{3、4、5、6、7、8}任意数字；
     * 第3—11位：0—9任意数字
     *
     * @param str
     * @return
     */
    public static boolean telPhoneNumber(String str) {
        if (str != null && str.length() == 11) {
            Pattern compile = Pattern.compile("^1[3|4|5|6|7|8|9][0-9]\\d{8}$");
            Matcher matcher = compile.matcher(str);
            return matcher.matches();
        }
        return false;
    }

    /**
     * 是否是UI线程
     *
     * @return
     */
    public static boolean isUiThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        if (height <= 0) {
            height = 60;  //获取不到，就设置60像素
        }
        return height;
    }


    /**
     * 判断是否有SD卡
     *
     * @return true为有SDcard，false则表示没有
     */
    public static boolean hasSdcard() {
        boolean hasCard = false;
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            hasCard = true;
        }
        return hasCard;
    }

    //判断email格式是否正确
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * Bitmap 转 Base64
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 把文本复制到粘贴板
     *
     * @param content
     */
    public static void clipContent(String content) {
        ClipboardManager cm = (ClipboardManager) WpkApp.mcx.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("Label", content);
        if (cm != null) {
            cm.setPrimaryClip(mClipData);
        }
    }


    public static int dp2px(Context context, int dip) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     **/
    public static String getNewContent(String htmltext) {
        try {
            Document doc = Jsoup.parse(htmltext);
            Elements elements = doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width", "100%").attr("height", "auto");
            }

            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }


    /**
     * 检测是否安装支付宝
     *
     * @param context
     * @return
     */
    public static boolean checkAliPayInstalled(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

    /**
     * 判断 用户是否安装微信客户端
     */
    public static boolean checkWxInstalled(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

}
